package com.csxy.six.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class OSSUtils {

    // 修改点1：更新属性名匹配配置文件
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    // 修改点2：使用 keyid 代替 accessKeyId
    @Value("${aliyun.oss.file.keyid}")
    private String accessKeyId;

    // 修改点3：使用 keysecret 代替 accessKeySecret
    @Value("${aliyun.oss.file.keysecret}")
    private String accessKeySecret;

    // 修改点4：使用 bucketname 代替 bucketName
    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    @Value("${aliyun.oss.file.folder}")
    private String folder;

    public String upload(MultipartFile file) throws Exception {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = folder + UUID.randomUUID().toString() + fileExtension;

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try (InputStream inputStream = file.getInputStream()) {
            // 上传文件
            ossClient.putObject(bucketName, fileName, inputStream);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 返回文件的URL
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}